<template>
  <div class="avatar-box">
    <van-uploader v-model="fileList" multiple :after-read="afterRead" />
    <van-button type="primary" @click="uploadAvatar">确认上传</van-button>
  </div>
</template>

<script>
import { uploadFile } from "@/service/mineService";
export default {
  data() {
    return {
      file: {},
      fileList: [
        {
          url: "https://img2.baidu.com/it/u=377342965,521277409&fm=253&fmt=auto&app=138&f=PNG?w=320&h=320",
          isImage: true,
        },
      ],
    };
  },

  methods: {
    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      this.file = file.file;
    },
    async uploadAvatar() {
      const file = this.file;
      let formdata = new FormData();
      formdata.append("file", file, file.name);
      const { data } = await uploadFile(formdata);
      // console.log(data);
      if (data.code !== 200) {
        return this.$toast("data.msg");
      } else {
        this.$emit("updateAvatar", data.url);
        this.$emit("changeAvatarShow");
        return this.$toast("上传成功");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-box {
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .van-uploader {
    margin-bottom: 30px;
  }
}
</style>
